<template>
  <div class="contract-template">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="模板名称">
          <el-input v-model="searchForm.templateName" placeholder="请输入模板名称" clearable />
        </el-form-item>
        <el-form-item label="模板类型">
          <el-select v-model="searchForm.templateType" placeholder="请选择模板类型" clearable>
            <el-option label="销售合同模板" value="SALE" />
            <el-option label="采购合同模板" value="PURCHASE" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.isEnabled" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">新增模板</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="templateName" label="模板名称" min-width="200" />
        <el-table-column prop="templateTypeName" label="模板类型" width="120" />
        <el-table-column prop="description" label="描述" min-width="300" show-overflow-tooltip />
        <el-table-column prop="isEnabledName" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isEnabled === 1 ? 'success' : 'danger'">
              {{ scope.row.isEnabledName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              :type="scope.row.isEnabled === 1 ? 'warning' : 'success'" 
              size="small" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.isEnabled === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板类型" prop="templateType">
              <el-select v-model="form.templateType" placeholder="请选择模板类型" style="width: 100%">
                <el-option label="销售合同模板" value="SALE" />
                <el-option label="采购合同模板" value="PURCHASE" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="模板内容" prop="templateContent">
          <el-input
            v-model="form.templateContent"
            type="textarea"
            :rows="15"
            placeholder="请输入模板内容，支持使用 {变量名} 格式定义变量"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-switch
            v-model="form.isEnabled"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模板详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="模板详情"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-if="templateDetail" class="template-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板名称">{{ templateDetail.templateName }}</el-descriptions-item>
          <el-descriptions-item label="模板类型">{{ templateDetail.templateTypeName }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="templateDetail.isEnabled === 1 ? 'success' : 'danger'">
              {{ templateDetail.isEnabledName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(templateDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(templateDetail.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ templateDetail.description || '无' }}</el-descriptions-item>
        </el-descriptions>

        <div class="template-content">
          <h3>模板内容</h3>
          <div class="content-preview">
            <pre>{{ templateDetail.templateContent }}</pre>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { contractApi } from '@/api/contract/contract'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: "contract_template",
  data() {
    return {
      // 搜索表单
      searchForm: {
        templateName: '',
        templateType: '',
        isEnabled: ''
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 表单数据
      form: {
        templateName: '',
        templateType: '',
        description: '',
        templateContent: '',
        isEnabled: 1
      },
      // 表单验证规则
      rules: {
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        templateType: [
          { required: true, message: '请选择模板类型', trigger: 'change' }
        ],
        templateContent: [
          { required: true, message: '请输入模板内容', trigger: 'blur' }
        ]
      },
      // 表单引用
      formRef: null,
      // 编辑模式
      isEdit: false,
      // 编辑的模板ID
      editId: null,
      // 详情对话框
      detailDialogVisible: false,
      // 模板详情数据
      templateDetail: null
    }
  },
  mounted() {
    this.loadTableData()
  },
  methods: {
    // 加载表格数据
    async loadTableData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          current: this.pagination.current,
          size: this.pagination.size
        }
        const res = await contractApi.getContractTemplatePage(params)
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        }
      } catch (error) {
        console.error('加载表格数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadTableData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        templateName: '',
        templateType: '',
        isEnabled: ''
      }
      this.handleSearch()
    },

    // 新增模板
    handleAdd() {
      this.isEdit = false
      this.editId = null
      this.dialogTitle = '新增合同模板'
      this.form = {
        templateName: '',
        templateType: '',
        description: '',
        templateContent: '',
        isEnabled: 1
      }
      this.dialogVisible = true
    },

    // 编辑模板
    handleEdit(row) {
      this.isEdit = true
      this.editId = row.id
      this.dialogTitle = '编辑合同模板'
      this.form = {
        templateName: row.templateName,
        templateType: row.templateType,
        description: row.description,
        templateContent: row.templateContent,
        isEnabled: row.isEnabled
      }
      this.dialogVisible = true
    },

    // 保存模板
    async handleSave() {
      try {
        await this.$refs.formRef.validate()
        
        if (this.isEdit) {
          // 编辑
          const res = await contractApi.updateContractTemplate(this.editId, this.form)
          if (res.code === 200) {
            ElMessage.success('模板更新成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          // 新增
          const res = await contractApi.addContractTemplate(this.form)
          if (res.code === 200) {
            ElMessage.success('模板创建成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('保存失败:', error)
      }
    },

    // 查看详情
    async handleView(row) {
      try {
        const res = await contractApi.getContractTemplateById(row.id)
        if (res.code === 200) {
          this.templateDetail = res.data
          this.detailDialogVisible = true
        } else {
          ElMessage.error(res.message || '获取模板详情失败')
        }
      } catch (error) {
        console.error('获取模板详情失败:', error)
        ElMessage.error('获取模板详情失败')
      }
    },

    // 切换状态
    async handleToggleStatus(row) {
      try {
        const action = row.isEnabled === 1 ? '禁用' : '启用'
        await ElMessageBox.confirm(`确定要${action}该模板吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const newStatus = row.isEnabled === 1 ? 0 : 1
        const res = await contractApi.updateContractTemplate(row.id, { isEnabled: newStatus })
        if (res.code === 200) {
          ElMessage.success(`${action}成功`)
          this.loadTableData()
        } else {
          ElMessage.error(res.message || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('切换状态失败:', error)
          ElMessage.error('切换状态失败')
        }
      }
    },

    // 删除模板
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await contractApi.deleteContractTemplate(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadTableData()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadTableData()
    },

    // 格式化日期时间
    formatDateTime(date) {
      if (!date) return ''
      return new Date(date).toLocaleString()
    }
  }
}
</script>

<style scoped>
.contract-template {
  padding: 20px;
}

.search-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.template-detail .el-descriptions {
  margin-bottom: 20px;
}

.template-content h3 {
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.content-preview {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  max-height: 400px;
  overflow-y: auto;
}

.content-preview pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}
</style>
